<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-header">
			<view class="search-box">
				<u-search
					v-model="searchKeyword"
					placeholder="搜索商品"
					@search="onSearch"
					@custom="onSearch"
					:show-action="true"
					action-text="搜索"
				></u-search>
			</view>
		</view>

		<!-- 搜索结果统计 -->
		<view class="search-stats" v-if="searchKeyword && searchKeyword.trim()">
			<view class="stats-info">
				<u-icon name="search" size="16" color="#FF4444"></u-icon>
				<text class="stats-text">搜索"{{ searchKeyword }}"的结果</text>
				<text class="stats-count">({{ total }}件商品)</text>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-container" v-if="goodsList.length > 0 && !loading">
			<view 
				class="goods-item" 
				v-for="(item, index) in goodsList.filter(item => item)" 
				:key="getGoodsKey(item, index)"
				@click="onGoodsClick(item, index)"
			>
				<view class="goods-image-container">
					<image 
						:src="(item && item.goodsImg) || (item && item.img) || '/static/logo.png'" 
						class="goods-img" 
						@error="onImageError" 
						@load="onImageLoad" 
						mode="aspectFill"
						:data-goods-id="(item && item.goodsId) || (item && item.id)"
					></image>
					<!-- 图片加载占位符 -->
					<view class="image-placeholder" v-if="item && !item.imageLoaded">
						<u-icon name="image" size="40" color="#ccc"></u-icon>
						<text class="placeholder-text">加载中...</text>
					</view>
					<!-- 商品标签 -->
					<view class="goods-tag" v-if="item && item.goodsKillType === 1">秒杀</view>
					<view class="goods-tag discount" v-else-if="item && item.goodsDiscountType === 1">折扣</view>
					<view class="goods-tag hot" v-else-if="item && item.sales > 1000">热销</view>
				</view>
				<view class="goods-info">
					<text class="goods-title">{{ (item && item.goodsName) || (item && item.title) || '商品名称' }}</text>
					<text class="goods-desc">{{ (item && item.goodsDesc) || (item && item.desc) || '商品描述' }}</text>
					<view class="goods-price-row">
						<text class="goods-price">¥{{ (item && item.goodsPrice) || (item && item.price) || '0.00' }}</text>
						<text class="goods-original-price" v-if="item && item.originalPrice && item.originalPrice !== item.goodsPrice">¥{{ item.originalPrice }}</text>
					</view>
					<view class="goods-meta">
						<text class="goods-sales">销量: {{ (item && item.sales) || 0 }}</text>
						<text class="goods-stock">库存: {{ (item && item.goodsNumber) || 0 }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore && goodsList.length > 0" @click="loadMore">
			<view class="load-more-content">
				<u-icon name="reload" size="16" color="#666"></u-icon>
				<text class="load-more-text">加载更多</text>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="goodsList.length === 0 && !loading && searchKeyword">
			<image src="/static/cart/空状态插图.png" class="empty-image" mode="aspectFit"></image>
			<text class="empty-text">未找到相关商品</text>
			<text class="empty-desc">试试其他关键词吧</text>
			<view class="empty-actions">
				<view class="retry-btn" @click="onSearch">
					<u-icon name="reload" size="16" color="#FF4444"></u-icon>
					<text class="retry-text">重新搜索</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading-state" v-if="loading">
			<view class="loading-content">
				<u-icon name="reload" size="20" color="#666" class="loading-icon"></u-icon>
				<text class="loading-text">搜索中...</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			searchKeyword: '',
			goodsList: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			hasMore: true,
			loading: false
		}
	},
	
	onLoad(options) {
		console.log('搜索结果页面加载，参数:', options);
		// 从首页传递过来的搜索关键词
		if (options.keyword) {
			this.searchKeyword = decodeURIComponent(options.keyword);
			console.log('解码后的搜索关键词:', this.searchKeyword);
			this.onSearch();
		}
	},
	
	methods: {
		// 搜索商品
		async onSearch() {
			if (!this.searchKeyword.trim()) {
				uni.showToast({
					title: '请输入搜索关键词',
					icon: 'none'
				});
				return;
			}

			this.pageNum = 1;
			this.hasMore = true;
			this.loading = true;
			
			uni.showLoading({
				title: '搜索中...'
			});
			
			try {
				const { goodsApi } = await import('../../utils/goodsApi.js');
				const result = await goodsApi.searchGoods(this.searchKeyword, {
					pageNum: this.pageNum,
					pageSize: this.pageSize
				});
				
				if (result && result.rows) {
					const processedGoods = result.rows.map(goods => {
						const goodsId = goods && (goods.goodsId || goods.id || goods.goodId);
						if (!goodsId) {
							console.warn('搜索商品ID缺失:', goods);
							return null;
						}
						
						return {
							goodsId: goodsId,
							goodsName: goods.goodsName || goods.title || goods.name || '商品名称',
							goodsDesc: goods.goodsDesc || goods.desc || goods.description || '商品描述',
							goodsPrice: goods.goodsPrice || goods.price || goods.sellingPrice || '0.00',
							originalPrice: goods.goodsDiscount || goods.originalPrice || goods.marketPrice || goods.goodsPrice || '0.00',
							goodsImg: goods.goodsImg || goods.img || goods.image || goods.pic || '/static/logo.png',
							sales: goods.sales || goods.soldCount || goods.sold || 0,
							goodsNumber: goods.goodsNumber || goods.stock || goods.inventory || 0,
							goodsKillType: goods.goodsKillType || 0,
							goodsDiscountType: goods.goodsDiscountType || 0,
							imageLoaded: false
						};
					}).filter(item => item !== null);
					
					this.goodsList = processedGoods;
					this.total = result.total || 0;
					this.hasMore = this.goodsList.length < this.total;
					
					uni.showToast({
						title: `找到${processedGoods.length}件相关商品`,
						icon: 'success',
						duration: 2000
					});
				} else {
					this.goodsList = [];
					this.total = 0;
					this.hasMore = false;
					
					uni.showToast({
						title: '未找到相关商品',
						icon: 'none',
						duration: 2000
					});
				}
			} catch (error) {
				console.error('搜索商品失败:', error);
				uni.showToast({
					title: '搜索失败，请重试',
					icon: 'none',
					duration: 2000
				});
			} finally {
				this.loading = false;
				uni.hideLoading();
			}
		},
		
		// 加载更多
		async loadMore() {
			if (!this.hasMore || this.loading) return;
			
			this.pageNum++;
			this.loading = true;
			
			try {
				const { goodsApi } = await import('../../utils/goodsApi.js');
				console.log('加载更多搜索，关键词:', this.searchKeyword, '页码:', this.pageNum);
				const result = await goodsApi.searchGoods(this.searchKeyword, {
					pageNum: this.pageNum,
					pageSize: this.pageSize
				});
				
				if (result && result.rows) {
					const processedGoods = result.rows.map(goods => {
						const goodsId = goods && (goods.goodsId || goods.id || goods.goodId);
						if (!goodsId) return null;
						
						return {
							goodsId: goodsId,
							goodsName: goods.goodsName || goods.title || goods.name || '商品名称',
							goodsDesc: goods.goodsDesc || goods.desc || goods.description || '商品描述',
							goodsPrice: goods.goodsPrice || goods.price || goods.sellingPrice || '0.00',
							originalPrice: goods.goodsDiscount || goods.originalPrice || goods.marketPrice || goods.goodsPrice || '0.00',
							goodsImg: goods.goodsImg || goods.img || goods.image || goods.pic || '/static/logo.png',
							sales: goods.sales || goods.soldCount || goods.sold || 0,
							goodsNumber: goods.goodsNumber || goods.stock || goods.inventory || 0,
							goodsKillType: goods.goodsKillType || 0,
							goodsDiscountType: goods.goodsDiscountType || 0,
							imageLoaded: false
						};
					}).filter(item => item !== null);
					
					this.goodsList = [...this.goodsList, ...processedGoods];
					this.hasMore = this.goodsList.length < this.total;
				}
			} catch (error) {
				console.error('加载更多失败:', error);
				this.pageNum--; // 回退页码
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 获取商品key值
		getGoodsKey(item, index) {
			if (item) {
				const goodsId = item.goodsId || item.id || item.goodId;
				if (goodsId) {
					return goodsId;
				}
			}
			return index;
		},
		
		// 点击商品
		onGoodsClick(goods, index) {
			const goodsId = goods && (goods.goodsId || goods.id || goods.goodId);
			
			if (goodsId) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${goodsId}`
				});
			} else {
				uni.showToast({
					title: `点击了商品${index + 1}`,
					icon: 'none'
				});
			}
		},
		
		// 图片加载完成
		onImageLoad(e) {
			const goodsId = e.currentTarget.dataset.goodsId;
			const item = this.goodsList.find(item => (item.goodsId || item.id) == goodsId);
			if (item) {
				item.imageLoaded = true;
			}
		},
		
		// 图片加载失败
		onImageError(e) {
			const goodsId = e.currentTarget.dataset.goodsId;
			const item = this.goodsList.find(item => (item.goodsId || item.id) == goodsId);
			if (item) {
				item.goodsImg = '/static/logo.png';
				item.imageLoaded = true;
			}
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 搜索头部 */
.search-header {
	background-color: #fff;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	position: sticky;
	top: 0;
	z-index: 100;
}

.search-box {
	width: 100%;
}

/* 搜索统计 */
.search-stats {
	background-color: #fff;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.stats-info {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.stats-text {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.stats-count {
	font-size: 24rpx;
	color: #666;
}

/* 商品容器 */
.goods-container {
	padding: 20rpx 30rpx;
}

.goods-item {
	display: flex;
	background-color: #fff;
	border-radius: 15rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	overflow: hidden;
	transition: all 0.3s ease;
}

.goods-item:active {
	transform: scale(0.98);
}

.goods-image-container {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	flex-shrink: 0;
}

.goods-img {
	width: 100%;
	height: 100%;
}

.image-placeholder {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #f8f9fa;
}

.placeholder-text {
	font-size: 24rpx;
	color: #999;
	margin-top: 10rpx;
}

.goods-tag {
	position: absolute;
	top: 10rpx;
	left: 10rpx;
	background-color: #FF4444;
	color: #fff;
	font-size: 20rpx;
	padding: 4rpx 8rpx;
	border-radius: 8rpx;
}

.goods-tag.discount {
	background-color: #FF9500;
}

.goods-tag.hot {
	background-color: #FF6B6B;
}

.goods-info {
	flex: 1;
	padding: 20rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.goods-title {
	font-size: 28rpx;
	font-weight: 500;
	color: #333;
	line-height: 1.4;
	margin-bottom: 10rpx;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.goods-desc {
	font-size: 24rpx;
	color: #999;
	line-height: 1.3;
	margin-bottom: 15rpx;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.goods-price-row {
	display: flex;
	align-items: center;
	gap: 10rpx;
	margin-bottom: 10rpx;
}

.goods-price {
	font-size: 32rpx;
	color: #FF4444;
	font-weight: bold;
}

.goods-original-price {
	font-size: 24rpx;
	color: #999;
	text-decoration: line-through;
}

.goods-meta {
	display: flex;
	justify-content: space-between;
	font-size: 22rpx;
	color: #999;
}

.goods-sales, .goods-stock {
	font-size: 22rpx;
	color: #999;
}

/* 加载更多 */
.load-more {
	text-align: center;
	padding: 30rpx;
	background-color: #fff;
	margin: 20rpx 30rpx;
	border-radius: 15rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	transition: background-color 0.2s ease;
}

.load-more:active {
	background-color: #f8f8f8;
}

.load-more-content {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
}

.load-more-text {
	font-size: 28rpx;
	color: #666;
}

/* 空状态 */
.empty-state {
	text-align: center;
	padding: 100rpx 30rpx;
	background-color: #fff;
	margin: 20rpx 30rpx;
	border-radius: 15rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
	opacity: 0.6;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 10rpx;
	display: block;
}

.empty-desc {
	font-size: 24rpx;
	color: #ccc;
	margin-top: 10rpx;
	display: block;
}

.empty-actions {
	margin-top: 30rpx;
	display: flex;
	justify-content: center;
	gap: 20rpx;
}

.retry-btn {
	background-color: #FF4444;
	color: #fff;
	padding: 15rpx 30rpx;
	border-radius: 30rpx;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	gap: 10rpx;
	box-shadow: 0 4rpx 15rpx rgba(255, 68, 68, 0.3);
}

.retry-btn:active {
	transform: scale(0.95);
	box-shadow: 0 2rpx 8rpx rgba(255, 68, 68, 0.3);
}

.retry-text {
	color: #fff;
}

/* 加载状态 */
.loading-state {
	text-align: center;
	padding: 50rpx 30rpx;
	background-color: #fff;
	margin: 20rpx 30rpx;
	border-radius: 15rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.loading-content {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
}

.loading-icon {
	animation: rotate 1s linear infinite;
}

@keyframes rotate {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}
</style> 